package cn.shyouchi.wuguanjia.android.ui.completeinfo;

import android.app.AlertDialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.widget.Button;
import android.widget.TextView;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.api.youchi.YouChiApi;
import cn.shyouchi.wuguanjia.android.base.BaseActivity;
import cn.shyouchi.wuguanjia.android.controls.AdvanceEditDialogFragment;
import cn.shyouchi.wuguanjia.android.controls.BasicEditDialogFragment;
import cn.shyouchi.wuguanjia.android.model.EmergencyContactMod;
import cn.shyouchi.wuguanjia.android.model.RegisterMod;
import cn.shyouchi.wuguanjia.android.model.User;
import cn.shyouchi.wuguanjia.android.subscribers.ProgressSubscriber;
import cn.shyouchi.wuguanjia.android.ui.EmergenctContactActivity;
import cn.shyouchi.wuguanjia.android.ui.MultiChoicesActivity;
import cn.shyouchi.wuguanjia.android.utils.LogUtil;
import cn.shyouchi.wuguanjia.android.utils.ToastUtil;
import cn.shyouchi.wuguanjia.android.widget.TopBar;
import cn.shyouchi.wuguanjia.android.widget.dialog.CongratulationDialogFragment;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class ImproveDetailInfoActivity extends BaseActivity implements
        DetailInfoContract.View {

    private static final String TAG = "ImproveDetailInfo";
    User mUser;
    @BindView(R.id.topBar)
    TopBar topBar;
    @BindView(R.id.rv_info)
    RecyclerView rvInfo;
    @BindView(R.id.register_eventually_submit_button)
    Button registerEventuallySubmitButton;
    UserInfoAdapter mAdapter;
    List<UserInfoModel> models = new ArrayList<>();
    UserInfoModel curModel;
    static final int EDIT_SKILL_REQUEST = 1001, EDIT_INDUSTRY_REQUEST = 1002, EDIT_EMERGENCY_CONTACT_REQUEST = 1003;
    static final String EMERGENCY_CONTACT_NAME = "emergency_contact_name";
    static final String EMERGENCY_CONTACT_RELATIONSHIP = "emergency_contact_relationship";
    static final String EMERGENCY_CONTACT_TELEPHONE = "emergency_contact_telephone";

    YouChiApi mApi;

    public static void start(Context context, User user) {
        Intent intent = new Intent(context, ImproveDetailInfoActivity.class);
        intent.putExtra("user", user);
        context.startActivity(intent);
    }


    @Override
    public int initContentView() {
        return R.layout.activity_improve_detail_info;
    }

    @Override
    public void initInjector() {
        mUser = getIntent().getParcelableExtra("user");
        if (mUser == null) {
            ToastUtil.showToast("用户信息无效");
            return;
        }

        mApi = new YouChiApi();
    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        topBar.setTitle(getTitle().toString());
        topBar.setLeftIcon(R.mipmap.ic_back);
        setSupportActionBar(topBar.getToolbar());
        models.add(new UserInfoModel(UserInfoModel.INFO_TYPE_HEIGHT, R.mipmap.ic_shengaoo, "身高", false));
        models.add(new UserInfoModel(UserInfoModel.INFO_TYPE_EDU, R.mipmap.ic_xueli, "学历", false));
        models.add(new UserInfoModel(UserInfoModel.INFO_TYPE_MARRIAGE, R.mipmap.ic_hunyin, "婚姻状况", false));
        models.add(new UserInfoModel(UserInfoModel.INFO_TYPE_ADDR, R.mipmap.ic_dizhi, "现居住地址", false));
        models.add(new UserInfoModel(UserInfoModel.INFO_TYPE_CONTACTS, R.mipmap.ic_lianxiren, "紧急联系人", false));
        models.add(new UserInfoModel(UserInfoModel.INFO_TYPE_FIRM, R.mipmap.ic_danweitijian, "现单位名称", false));
        models.add(new UserInfoModel(UserInfoModel.INFO_TYPE_TRADE, R.mipmap.ic_industry, "行业", false));
        models.add(new UserInfoModel(UserInfoModel.INFO_TYPE_SKILL, R.mipmap.ic_skill, "技能", false));
        models.add(new UserInfoModel(UserInfoModel.INFO_TYPE_CHANNEL, R.mipmap.ic_channel, "应聘渠道", false));
        mAdapter = new UserInfoAdapter(models, this);
        rvInfo.setAdapter(mAdapter);
        rvInfo.setLayoutManager(new LinearLayoutManager(mContext));
    }


    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }


    @Override
    public void infoItemClick(UserInfoModel model) {
        switch (model.getType()) {
            case UserInfoModel.INFO_TYPE_HEIGHT:
                showHeightEditDialog(model);
                break;
            case UserInfoModel.INFO_TYPE_EDU:
                graduateEditDialog(model);
                break;
            case UserInfoModel.INFO_TYPE_MARRIAGE:
                weddingEditDialog(model);
                break;
            case UserInfoModel.INFO_TYPE_ADDR:
                addressEditTapped(model);
                break;
            case UserInfoModel.INFO_TYPE_CONTACTS:
                emergencyContactEditTapped(model);
                break;
            case UserInfoModel.INFO_TYPE_FIRM:
                showCompanyEditDialog(model);
                break;
            case UserInfoModel.INFO_TYPE_TRADE:
                showIndustryEditDialog(model);
                break;
            case UserInfoModel.INFO_TYPE_SKILL:
                skillEditTapped(model);
                break;
            case UserInfoModel.INFO_TYPE_CHANNEL:
                channelEditDialog(model);
                break;
        }
    }

    void showCompanyEditDialog(final UserInfoModel model) {
        BasicEditDialogFragment dialog = BasicEditDialogFragment.newInstance("现单位名称", "请输入您的现单位名称", InputType.TYPE_CLASS_TEXT, false);
        dialog.setEnterClickListener(new BasicEditDialogFragment.BasicEditDialogListener() {
            @Override
            public void onBasicEditDialogPositiveClick(DialogFragment dialog, String content) {
                model.setValue(content);
                mAdapter.notifyDataSetChanged();
            }
        });
        dialog.show(getFragmentManager(), "CompanyEditDialogFragment");
    }

    void showHeightEditDialog(final UserInfoModel model) {
        BasicEditDialogFragment dialog = BasicEditDialogFragment.newInstance("身高", "请输入您的身高 例如: 175", InputType.TYPE_CLASS_NUMBER, false);
        dialog.setEnterClickListener(new BasicEditDialogFragment.BasicEditDialogListener() {
            @Override
            public void onBasicEditDialogPositiveClick(DialogFragment dialog, String content) {
                model.setValue(String.format("%s", content));
                mAdapter.notifyDataSetChanged();
            }
        });

        dialog.show(getFragmentManager(), "HeightEditDialogFragment");
    }

    void graduateEditDialog(final UserInfoModel model) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT);
        TextView tvTitle = (TextView) getLayoutInflater().inflate(R.layout.dialog_title, null);
        tvTitle.setText("选择学历");
        builder.setCustomTitle(tvTitle);
        final String[] graduates = new String[]{"小学", "初中", "高中", "专科", "本科", "研究生", "博士"};
        builder.setItems(graduates, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                model.setValue(graduates[which]);
                dialog.dismiss();
                mAdapter.notifyDataSetChanged();
            }
        });
        builder.setNegativeButton("取消", null);
        builder.create().show();
    }

    void weddingEditDialog(final UserInfoModel model) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT);
        TextView tvTitle = (TextView) getLayoutInflater().inflate(R.layout.dialog_title, null);
        tvTitle.setText("婚姻状况");
        builder.setCustomTitle(tvTitle);
        final String[] graduates = new String[]{"未婚", "已婚"};
        builder.setItems(graduates, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                model.setValue(graduates[which]);
                dialog.dismiss();
                mAdapter.notifyDataSetChanged();
            }
        });
        builder.setNegativeButton("取消", null);
        builder.create().show();
    }

    void addressEditTapped(final UserInfoModel model) {
        BasicEditDialogFragment dialog = BasicEditDialogFragment.newInstance("现居住地址", "请输入您的现居住地址", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE, true);
        dialog.setEnterClickListener(new BasicEditDialogFragment.BasicEditDialogListener() {
            @Override
            public void onBasicEditDialogPositiveClick(DialogFragment dialog, String content) {
                model.setValue(content);
                mAdapter.notifyDataSetChanged();
            }
        });
        dialog.show(getFragmentManager(), "AddressEditDialogFragment");
    }


    private void skillEditTapped(UserInfoModel model) {
        curModel = model;
        Intent i = new Intent(this, MultiChoicesActivity.class);
        Bundle b = new Bundle();
        b.putString("title", "技能");
        b.putStringArray("choices", new String[]{"武术", "散打", "拳击", "退伍", "美术", "驾照", "其他"});
        b.putString("edit_dialog_title", "技能");
        b.putString("edit_dialog_hint", "请输入您的技能");
        i.putExtras(b);
        startActivityForResult(i, EDIT_SKILL_REQUEST);
    }

    void showIndustryEditDialog(final UserInfoModel model) {
        curModel = model;
        Intent i = new Intent(this, MultiChoicesActivity.class);
        Bundle b = new Bundle();
        b.putString("title", "行业");
        b.putStringArray("choices", new String[]{"保安", "消防", "工程", "保洁", "物业", "其他"});
        b.putString("edit_dialog_title", "行业");
        b.putString("edit_dialog_hint", "请输入您的行业");
        i.putExtras(b);
        startActivityForResult(i, EDIT_INDUSTRY_REQUEST);
    }


    void emergencyContactEditTapped(final UserInfoModel model) {
        Intent i = new Intent(this, EmergenctContactActivity.class);
        curModel = model;
        startActivityForResult(i, EDIT_EMERGENCY_CONTACT_REQUEST);
    }

    void channelEditDialog(final UserInfoModel model) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT);
        TextView tvTitle = (TextView) getLayoutInflater().inflate(R.layout.dialog_title, null);
        tvTitle.setText("应聘渠道");
        builder.setCustomTitle(tvTitle);
        final String[] graduates = new String[]{"赶集网", "58同城", "劳务介绍所", "朋友介绍"};
        builder.setItems(graduates, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == 2) {
                    AdvanceEditDialogFragment dia = AdvanceEditDialogFragment.newInstance(
                            "应聘渠道", "劳务介绍所", "请输入劳务介绍所的名称", "请输入劳务介绍所的电话号码");
                    dia.setClickListener(new AdvanceEditDialogFragment.AdvanceEditDialogListener() {
                        @Override
                        public void onAdvanceEditDialogPositiveClick(DialogFragment dialog, String content1, String content2) {
                            String channel = content1 + "/" + content2;
                            model.setValue(channel);
                            mUser.setChannel(channel);
                            mAdapter.notifyDataSetChanged();
                        }
                    });
                    dia.show(getFragmentManager(), "AgentEditDialogFragment");
                } else if (which == 3) {
                    AdvanceEditDialogFragment di = AdvanceEditDialogFragment.newInstance("应聘渠道", "朋友介绍", "请输入朋友的名称", "请输入朋友的电话号码");
                    di.setClickListener(new AdvanceEditDialogFragment.AdvanceEditDialogListener() {
                        @Override
                        public void onAdvanceEditDialogPositiveClick(DialogFragment dialog, String content1, String content2) {
                            String channel = content1 + "/" + content2;
                            model.setValue(channel);
                            mUser.setChannel(channel);
                            mAdapter.notifyDataSetChanged();
                        }
                    });
                    di.show(getFragmentManager(), "FriendEditDialogFragment");

                } else {
                    model.setValue(graduates[which]);
                    dialog.dismiss();
                    mAdapter.notifyDataSetChanged();
                }

            }
        });
        builder.setNegativeButton("取消", null);
        builder.create().show();
    }


    @OnClick(R.id.register_eventually_submit_button)
    public void submit() {
        boolean filled = true;
        for (UserInfoModel model : models) {
            if (model.isFilled()) {
                switch (model.getType()) {
                    case UserInfoModel.INFO_TYPE_HEIGHT:
                        mUser.setHeight(Integer.parseInt(model.getValue()));
                        break;
                    case UserInfoModel.INFO_TYPE_EDU:
                        mUser.setGraduate(model.getValue());
                        break;
                    case UserInfoModel.INFO_TYPE_MARRIAGE:
                        mUser.setWedding(model.getValue());
                        break;
                    case UserInfoModel.INFO_TYPE_ADDR:
                        mUser.setLivingAddress(model.getValue());
                        break;
                    case UserInfoModel.INFO_TYPE_CONTACTS:
//                        mUser.setGraduate(model.getValue());
                        break;
                    case UserInfoModel.INFO_TYPE_FIRM:
                        mUser.setCompany(model.getValue());
                        break;
                    case UserInfoModel.INFO_TYPE_TRADE:
//                        mUser.setIndustry(model.getValue());
                        break;
                    case UserInfoModel.INFO_TYPE_SKILL:
//                        mUser.setSkill(model.getValue());
                        break;
                    case UserInfoModel.INFO_TYPE_CHANNEL:
                        mUser.setChannel(model.getValue());
                        break;
                }
            } else {
                filled = false;
                model.setFillError();
            }
        }
        if (filled) {
            LogUtil.json(mUser);
            mApi.register(mUser)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new ProgressSubscriber<RegisterMod>(mContext) {
                        @Override
                        public void onNext(RegisterMod registerMod) {
                            CongratulationDialogFragment dialog = new CongratulationDialogFragment();
                            dialog.setonClickListener(new CongratulationDialogFragment.CongratulationDialogListener() {
                                @Override
                                public void onCongratulationDialogPositiveClick(DialogFragment dialog) {
                                    finish();
                                    dialog.dismiss();
                                }

                                @Override
                                public void onCongratulationDialogTimeUp(DialogFragment dialog) {
                                    finish();
                                    dialog.dismiss();
                                }
                            });
                            dialog.show(getFragmentManager(), "CongratulationDialogFragment");
                        }
                    });
        } else {
            ToastUtil.showToast("信息没有填写完整");
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == EDIT_INDUSTRY_REQUEST && resultCode == RESULT_OK) {
            String industry = "";
            ArrayList<String> industryArrayList = data.getStringArrayListExtra("CHOICES");
            for (int i = 0; i < industryArrayList.size(); i++) {
                industry += industryArrayList.get(i);
                if (i != industryArrayList.size() - 1) {
                    industry += "/";
                }
            }
            curModel.setValue(industry);
            mUser.setIndustry(new JSONArray(industryArrayList).toString());
            mAdapter.notifyDataSetChanged();

        } else if (requestCode == EDIT_SKILL_REQUEST && resultCode == RESULT_OK) {
            String skill = "";
            ArrayList<String> industryArrayList = data.getStringArrayListExtra("CHOICES");
            for (int i = 0; i < industryArrayList.size(); i++) {
                skill += industryArrayList.get(i);
                if (i != industryArrayList.size() - 1) {
                    skill += "/";
                }
            }
            curModel.setValue(skill);
            mUser.setSkill(new JSONArray(industryArrayList).toString());
            mAdapter.notifyDataSetChanged();
        } else if (requestCode == EDIT_EMERGENCY_CONTACT_REQUEST && resultCode == RESULT_OK) {
            String name = data.getStringExtra(EMERGENCY_CONTACT_NAME);
            String relationship = data.getStringExtra(EMERGENCY_CONTACT_RELATIONSHIP);
            String telephone = data.getStringExtra(EMERGENCY_CONTACT_TELEPHONE);
            EmergencyContactMod contactMod = new EmergencyContactMod(name, relationship, telephone);
            mUser.setEmergencyContact(contactMod);
            curModel.setValue(contactMod.toString());
            mAdapter.notifyDataSetChanged();
        }
    }


}
